package com.jing.system.comm;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jing.system.comm.contants.SystemCons;
import com.jing.system.utils.FileUtil;
import com.jing.taobao.pojo.user.TaobaoUser;
import com.jing.weibo.pojo.user.UserInfo;

/**
 * 上传文件的Controller
 * @author jing.yue
 * @version 2012/10/25 1.0.0
 */
@Controller
public class FileController extends BaseController {

	private static final Logger logger = Logger.getLogger(FileController.class);

	/**
	 * 上传文件
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public String uploadSolver(HttpServletRequest request, String type) {
    	String username = null;
    	if("taobao".equals(type)) {
    		TaobaoUser taobaoUser = getSessionTaobaoUser(request);
        	logger.info(taobaoUser.getNickname() + ": 上传文件!");
        	username = taobaoUser.getUsername();
        	logger.info(taobaoUser.getNickname() + ": TAOBAO上传文件!");
    	} else {
	    	UserInfo userInfo = getSessionUser(request);
	    	username = userInfo.getUsername();
        	logger.info(userInfo.getNickname() + ": WEIBO上传文件!");
    	}
    	String result = null;

    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    	//获得文件
		MultipartFile multipartFile = multipartRequest.getFile("file");

        //获得原始文件名
		String orgFileName = multipartFile.getOriginalFilename();

		//文件名[用户名_时间戳]
		String fileName = username + "_" + System.currentTimeMillis() + orgFileName.substring(orgFileName.lastIndexOf("."), orgFileName.length());
		try {
			//获得输入流
			//InputStream input = multipartFile.getInputStream();

			//写入文件
			FileUtil.createDir(SystemCons.ABSOLUTE_PATH + File.separator + SystemCons.UPLOAD_IMAGE_PATH);
			File source = new File(SystemCons.ABSOLUTE_PATH + File.separator + SystemCons.UPLOAD_IMAGE_PATH + fileName);
			multipartFile.transferTo(source);
			result = SUCCESS;
		} catch (IllegalStateException e) {
			logger.error(e.getMessage(), e);
			result = ERROR;
		}
		catch (IOException e) {
			logger.error(e.getMessage(), e);
			result = ERROR;
		}

    	StringBuffer resultBuffer = new StringBuffer("{");
    	resultBuffer.append("result:'" + result);
    	resultBuffer.append("',orgFileName:'"+ orgFileName);
    	resultBuffer.append("',fileName:'"+ fileName+"'}");
		return resultBuffer.toString();
	}

}